import java.time.LocalDateTime;
import java.util.List;

public class TicketService {
    private TicketDao ticketDao = new TicketDaoImpl();
    private int ticketIdCounter = 1;

    // 售票
    public Ticket sellTicket(Show show, int seatRow, int seatCol) {
        // 检查座位是否已售出
        if (isSeatSold(show, seatRow, seatCol)) {
            return null;
        }

        // 创建新票
        String ticketId = "T" + String.format("%06d", ticketIdCounter++);
        Ticket ticket = new Ticket(ticketId, show, seatRow, seatCol);
        
        if (ticketDao.addTicket(ticket)) {
            return ticket;
        }
        return null;
    }

    // 退票
    public boolean refundTicket(String ticketId) {
        Ticket ticket = ticketDao.getTicketById(ticketId);
        if (ticket == null || !ticket.canRefund()) {
            return false;
        }

        ticket.setRefunded(true);
        return ticketDao.updateTicketRefundStatus(ticketId, true);
    }

    // 检查座位是否已售出
    public boolean isSeatSold(Show show, int seatRow, int seatCol) {
        List<Ticket> tickets = ticketDao.getTicketsByShowId(show.getShowId());
        for (Ticket ticket : tickets) {
            if (!ticket.isRefunded() && 
                ticket.getSeatRow() == seatRow && 
                ticket.getSeatCol() == seatCol) {
                return true;
            }
        }
        return false;
    }
}
    